package com.urbanski.clipboard.client.action;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ClipboardClient;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.message.PauseMessage;
import com.urbanski.util.logging.LoggingUtil;

public class PauseActionHandler extends ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(PauseActionHandler.class);

	private String server;
	private Set<String> sessions;

	public PauseActionHandler(String[] tokens)
	{
		super(ClientCommand.PAUSE, tokens);
	}

	@Override
	public void execute()
	{
		processArgs();
		
		if (server == null)
		{
			Map<String, ServerConnection> connections = ClipboardClient.getConnections();
			synchronized (connections)
			{
				for (Entry<String, ServerConnection> c : connections.entrySet())
				{
					synchronized (c.getValue())
					{
						try
						{
							c.getValue().sendMessage(new PauseMessage(new HashSet<String>()));
							LoggingUtil.logAndPrintInfo(LOGGER, "Paused all sessions on server " + c.getKey());
						}
						catch (IOException e)
						{
							LoggingUtil.logAndPrintError(LOGGER, "Error pausing sessions on server " + c.getKey(), e);
						}
					}
				}
			}
		}
		else if (tokens == null)
		{
			ServerConnection c = ClipboardClient.findConnection(server);

			synchronized (c)
			{
				try
				{
					c.sendMessage(new PauseMessage(new HashSet<String>()));
					LoggingUtil.logAndPrintInfo(LOGGER, "Paused all sessions on server " + server);
				}
				catch (IOException e)
				{
					LoggingUtil.logAndPrintError(LOGGER, "Error pausing sessions on server " + server, e);
				}
			}
		}
		else
		{
			ServerConnection c = ClipboardClient.findConnection(server);

			synchronized (c)
			{
				try
				{
					c.sendMessage(new PauseMessage(sessions));
					LoggingUtil.logAndPrintInfo(LOGGER, "Paused sessions on server " + server);
				}
				catch (IOException e)
				{
					LoggingUtil.logAndPrintError(LOGGER, "Error pausing sessions on server " + server, e);
				}
			}
		}
	}

	private void processArgs()
	{
		if (tokens.length == 1)
		{
			return;
		}
		else
		{
			server = tokens[1];
			sessions = new HashSet<>();
			for (int i = 2; i < tokens.length; i++)
			{
				sessions.add(tokens[i]);
			}
		}
	}

}
